﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;

namespace WPF.CustomControl
{

    public class TextBlockAttacher
    {
        private const double FontSizeConstant = (double)4 / 3;  // 1/3 = lines spacing

        public static readonly DependencyProperty LimitedLineNumberProperty = DependencyProperty.RegisterAttached
            ("LimitedLineNumber",
             typeof(int),
             typeof(TextBlockAttacher),
             new FrameworkPropertyMetadata(new PropertyChangedCallback(LimitedLineNumberChanged)));

        public static void SetLimitedLineNumber(DependencyObject target, int value)
        {
            target.SetValue(TextBlockAttacher.LimitedLineNumberProperty, value);
        }

        private static void LimitedLineNumberChanged(DependencyObject target, DependencyPropertyChangedEventArgs e)
        {
            TextBlock txtBlock = target as TextBlock;

            if (txtBlock != null)
            {
                if (((int)e.NewValue != 0) && ((int)e.OldValue == 0))
                {
                    txtBlock.Loaded += txtBlock_Loaded;
                }
                else if (((int)e.NewValue == 0) && ((int)e.OldValue != 0))
                {
                    txtBlock.Loaded -= txtBlock_Loaded;
                }
            }
        }

        private static void txtBlock_Loaded(object sender, RoutedEventArgs e)
        {
            TextBlock txtBlock = sender as TextBlock;
            if (txtBlock != null)
            {
                int lineNumber = (int)txtBlock.GetValue(TextBlockAttacher.LimitedLineNumberProperty);
                double fontSize = txtBlock.FontSize * FontSizeConstant;
                txtBlock.MaxHeight = lineNumber * fontSize;
            }
        }

    }

}
